#pragma once
#include <iostream>
#include <pthread.h>
#include <cstring>
#include <cstdio>

namespace MyMutex
{
    class Mutex
    {
    public:
        Mutex()
        {
            pthread_mutex_init(&_plock, nullptr); // 锁初始化
        }
        void Lock() // 加锁
        {
            int n = pthread_mutex_lock(&_plock);
            if (n != 0)
                std::cerr << "pthread_mutex_lock fail: " << strerror(n) << std::endl;
        }
        void UnLock() // 解锁
        {
            int n = pthread_mutex_unlock(&_plock);
            if (n != 0)
                std::cerr << "pthread_mutex_unlock fail: " << strerror(n) << std::endl;
        }

        pthread_mutex_t *GetMutex()
        {
            return &_plock;
        }

        ~Mutex()
        {
            pthread_mutex_destroy(&_plock); 
        }

    private:
        pthread_mutex_t _plock;
    };

    class LockGuard
    {
    public:
        LockGuard(Mutex *mutex)
            : _mutex(mutex)
        {
            _mutex->Lock(); // 构造时加锁
        }

        ~LockGuard()
        {
            _mutex->UnLock(); // 析构时解锁
        }

    private:
        Mutex *_mutex;
    };
}